﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Windows;

using Game.Common;

namespace Game.Map.Internal
{
    [DataContract(Namespace="game")]
    class GameMapView : GameMapWrapper, IGameMapView
    {
        public event EventHandler<MapEventArgs> Dirty;
        public event EventHandler<MapViewEventArgs> AfterResetVisible;
        
        readonly GamePlayer _Owner;
        readonly MapFieldViewCollection _Collection;
        
        public GameMapView(IGameMap gameMap, GamePlayer owner)
            : base(gameMap)
        {
            _Owner = owner;
            _Collection = new MapFieldViewCollection();

            foreach (MapField field in GameMap.Fields)
            {
                var view = new MapFieldView(field);
                _Collection.Add(view);
            }

            GameMap.Dirty += delegate(object sender, MapEventArgs e) 
            {
                if (Dirty != null)
                {
                    Dirty(this, e);
                }
            };

        }

        public GamePlayer Owner
        { 
            get { return _Owner; }
        }
        
        public MapFieldViewCollection Collection
        {
            get { return _Collection; }
        }
        
        public MapFieldViewCollection ViewFields 
        {
            get { return Convert(GameMap.Fields); }
        }

        public void ResetVisible()
        {
            foreach (var field in Collection)
            {
                field.IsVisible = false;
            }

            if (AfterResetVisible != null)
            {
                AfterResetVisible(this, new MapViewEventArgs(this));
            }
        }

        MapFieldViewCollection Convert(IEnumerable<IMapField> collection)
        {
            var result = new MapFieldViewCollection();
            
            foreach (var field in collection) 
            {
                result.Add(_Collection[field.Point]);
            }
            
            return result;
        }
    }

    public class MapFieldViewCollection : KeyedCollection<Point, IMapFieldView>
    {
        protected override Point GetKeyForItem(IMapFieldView item)
        {
            return item.Point;
        }
    }

}
